// 全局时间同步服务
import { ref, computed } from 'vue'

// 时间格式化选项
export interface TimeDisplayOptions {
  showMilliseconds: boolean
  use24Hour: boolean
  showDate: boolean
}

// 时间数据接口
export interface TimeData {
  timestamp: number
  formatted: string
  formattedWithMs: string
  date: string
  time: string
  milliseconds: number
}

class TimeService {
  private static instance: TimeService
  private updateTimer: NodeJS.Timeout | null = null
  private subscribers = new Set<(timeData: TimeData) => void>()
  
  // 响应式时间数据
  public currentTime = ref('')
  public currentTimeWithMs = ref('')
  public currentTimestamp = ref(0)
  public isRunning = ref(false)
  
  // 收盘闪烁状态
  public isFlashing = ref(false)
  private flashInterval: NodeJS.Timeout | null = null
  
  // 配置选项
  private options: TimeDisplayOptions = {
    showMilliseconds: true,
    use24Hour: true,
    showDate: false
  }

  private constructor() {
    this.startTimeUpdate()
    this.setupFlashListeners()
  }
  
  // 设置收盘闪烁监听器
  private setupFlashListeners() {
    // 监听收盘前闪烁事件
    window.addEventListener('market-close-flash', () => {
      this.startFlashing()
    })
    
    // 监听停止闪烁事件
    window.addEventListener('market-close-stop-flash', () => {
      this.stopFlashing()
    })
  }
  
  // 开始闪烁
  private startFlashing() {
    if (this.flashInterval) {
      return // 已经在闪烁中
    }
    
    console.log('⚠️ [TimeService] 开始收盘闪烁')
    this.isFlashing.value = true
    
    // 每500ms切换一次闪烁状态
    this.flashInterval = setInterval(() => {
      this.isFlashing.value = !this.isFlashing.value
    }, 500)
  }
  
  // 停止闪烁
  private stopFlashing() {
    if (this.flashInterval) {
      clearInterval(this.flashInterval)
      this.flashInterval = null
    }
    this.isFlashing.value = false
    console.log('✅ [TimeService] 停止收盘闪烁')
  }

  public static getInstance(): TimeService {
    if (!TimeService.instance) {
      TimeService.instance = new TimeService()
    }
    return TimeService.instance
  }

  // 设置显示选项
  public setOptions(options: Partial<TimeDisplayOptions>) {
    this.options = { ...this.options, ...options }
    this.updateTime() // 立即更新显示
  }

  // 获取当前选项
  public getOptions(): TimeDisplayOptions {
    return { ...this.options }
  }

  // 订阅时间更新
  public subscribe(callback: (timeData: TimeData) => void): () => void {
    this.subscribers.add(callback)
    
    // 立即发送当前时间
    callback(this.getCurrentTimeData())
    
    // 返回取消订阅函数
    return () => {
      this.subscribers.delete(callback)
    }
  }

  // 获取当前时间数据
  private getCurrentTimeData(): TimeData {
    const now = new Date()
    const timestamp = now.getTime()
    
    const hours = now.getHours().toString().padStart(2, '0')
    const minutes = now.getMinutes().toString().padStart(2, '0')
    const seconds = now.getSeconds().toString().padStart(2, '0')
    const milliseconds = now.getMilliseconds()
    const ms = milliseconds.toString().padStart(3, '0')
    
    const time = `${hours}:${minutes}:${seconds}`
    const timeWithMs = `${time}.${ms}`
    
    const year = now.getFullYear()
    const month = (now.getMonth() + 1).toString().padStart(2, '0')
    const day = now.getDate().toString().padStart(2, '0')
    const date = `${year}-${month}-${day}`
    
    let formatted = time
    if (this.options.showMilliseconds) {
      formatted = timeWithMs
    }
    if (this.options.showDate) {
      formatted = `${date} ${formatted}`
    }
    
    return {
      timestamp,
      formatted,
      formattedWithMs: timeWithMs,
      date,
      time,
      milliseconds
    }
  }

  // 更新时间
  private updateTime() {
    const timeData = this.getCurrentTimeData()
    // 更新响应式数据
    this.currentTime.value = timeData.time
    this.currentTimeWithMs.value = timeData.formattedWithMs
    this.currentTimestamp.value = timeData.timestamp
    
    // 通知所有订阅者
    this.subscribers.forEach(callback => {
      try {
        callback(timeData)
      } catch (error) {
        console.error('时间更新回调执行失败:', error)
      }
    })
  }

  // 启动时间更新
  public startTimeUpdate(intervalMs: number = 100) {
    if (this.updateTimer) {
      this.stopTimeUpdate()
    }
    
    this.updateTime() // 立即更新一次
    this.updateTimer = setInterval(() => {
      this.updateTime()
    }, intervalMs)
    
    this.isRunning.value = true
  }

  // 停止时间更新
  public stopTimeUpdate() {
    if (this.updateTimer) {
      clearInterval(this.updateTimer)
      this.updateTimer = null
      this.isRunning.value = false
    }
  }

  // 设置更新频率
  public setUpdateInterval(intervalMs: number) {
    if (this.isRunning.value) {
      this.startTimeUpdate(intervalMs)
    }
  }

  // 获取格式化时间（静态方法）
  public static formatTime(timestamp: number, options?: Partial<TimeDisplayOptions>): string {
    const date = new Date(timestamp)
    const opts = {
      showMilliseconds: true,
      use24Hour: true,
      showDate: false,
      ...options
    }
    
    const hours = date.getHours().toString().padStart(2, '0')
    const minutes = date.getMinutes().toString().padStart(2, '0')
    const seconds = date.getSeconds().toString().padStart(2, '0')
    const ms = date.getMilliseconds().toString().padStart(3, '0')
    
    let time = `${hours}:${minutes}:${seconds}`
    if (opts.showMilliseconds) {
      time += `.${ms}`
    }
    
    if (opts.showDate) {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      time = `${year}-${month}-${day} ${time}`
    }
    
    return time
  }

  // 解析CTP时间戳
  public static parseCTPTime(updateTime: string, updateMillisec: number): Date {
    // CTP时间格式通常是 "HH:MM:SS"
    const today = new Date()
    const [hours, minutes, seconds] = updateTime.split(':').map(Number)
    
    const ctpDate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), hours, minutes, seconds, updateMillisec)
    return ctpDate
  }

  // 格式化CTP时间
  public static formatCTPTime(updateTime: string, updateMillisec: number, options?: Partial<TimeDisplayOptions>): string {
    const ctpDate = TimeService.parseCTPTime(updateTime, updateMillisec)
    return TimeService.formatTime(ctpDate.getTime(), options)
  }

  // 销毁服务
  public destroy() {
    this.stopTimeUpdate()
    this.stopFlashing()
    this.subscribers.clear()
  }
}

// 导出单例实例
export const timeService = TimeService.getInstance()

// 导出便捷的组合式API
export function useGlobalTime(options?: Partial<TimeDisplayOptions>) {
  const service = TimeService.getInstance()
  
  if (options) {
    service.setOptions(options)
  }
  
  return {
    currentTime: computed(() => service.currentTime.value),
    currentTimeWithMs: computed(() => service.currentTimeWithMs.value),
    currentTimestamp: computed(() => service.currentTimestamp.value),
    isRunning: computed(() => service.isRunning.value),
    isFlashing: computed(() => service.isFlashing.value),
    setOptions: (opts: Partial<TimeDisplayOptions>) => service.setOptions(opts),
    setUpdateInterval: (intervalMs: number) => service.setUpdateInterval(intervalMs)
  }
}

export default TimeService
